﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Comm;

public partial class _login : PublicPage
{
    private BLL.Admin bll = new BLL.Admin();
    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "set_pwd", "var pwd='" + CookiesHelper.GetCookieValue("companylogin") + "';", true);
    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void but_login_Click(object sender, EventArgs e)
    {
        string username = txt_UserName.Text.Trim();
        string password = txt_Password.Text.Trim();
        string yancode = txt_YanCode.Text.Trim();

        object ValidateCodeImage = Session["ValidateCodeImage"];
        if (!txt_YanCodeImage.Equals(yancode))
        {
            MessageBox.Show("抱歉，验证码错误。不能让你登录。");
        }

        Model.Admin model = bll.GetModelByUserName(username);
        if (model == null)
        {
            MessageBox.Show("该用户不存在");
        }
        if (model.Password.ToLower().Trim() != password.ToLower().Trim())
        {
            MessageBox.Show("密码输入错误");
        }

        if (chk_Remember.Checked)
        {
            CookiesHelper.AddCookie("companylogin", model.Username + "+" + model.Password, DateTime.Now.AddDays(30));
        }

        Session["admin"] = model;
        AddLog(model);

        Model.Admin newmodel = new Model.Admin();
        newmodel.ID = model.ID;
        newmodel.Lastloginip = Request.UserHostAddress;
        model.Lastlogintime = DateTime.Now;
        bll.UpdateLogin(newmodel);
        
        Response.Redirect("default.aspx");
    }

    /// <summary>
    /// 添加登录日志
    /// </summary>
    /// <param name="myuser"></param>
    private void AddLog(Model.Admin myuser)
    {
        Model.AdminLog model = new Model.AdminLog();
        model.UserName = myuser.Username;
        model.OperationTypes = 0;
        model.ODescription = "登录成功";
        model.IP = Request.UserHostAddress.Trim();
        model.AddTime = DateTime.Now;

        new BLL.AdminLog().Add(model);
    }
}
